<?php

namespace App\Trip\Epidemic\Juhe;

// 支持城市清单查询
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class City extends JuheAbstract
{
    public array   $dictionary
                        = [
            '伊宁'     => '伊犁',
            '北京城区' => '北京',
        ];
    private string $url = 'http://apis.juhe.cn/springTravel/citys';
    private string $file;

    public function __construct()
    {
        parent:: __construct();
        $this->file = public_path('Epidemic/city.json');
    }

    public function query($param = []): static
    {
        $url    = sprintf($this->url."?key=%s", $this->key);
        $getRes = function ($url) {
            $res      = $this->client->get($url);
            $contents = json_decode($res->getBody()->getContents(), true);
            file_put_contents($this->file, json_encode($contents['result'] ?? '', JSON_UNESCAPED_UNICODE));
        };
        // 如果文件不存在或者文件内容为空
        if (!file_exists($this->file) || empty(json_decode(file_get_contents($this->file), true))) {
            $getRes($url);
        } else {
            // 获取文件修改时间
            $updated_at = filemtime($this->file);
            // 每30天更新一次
            if (Carbon::createFromTimestamp($updated_at)->diffInDays(Carbon::now()) > 30) {
                $getRes($url);
            }

        }
        return $this;
    }

    /**
     * @throws Exception
     */
    public function getCodeByName(string $name): string
    {
        $name = $this->dictionary[$name] ?? $name;
        // 城市不含市字 过滤
        $name               = Str::replaceLast('市', '', $name);
        $name               = Str::replaceLast('城区', '', $name);
        $cache_key          = "Epidemic:city_id:{$name}";
        $collapse_cache_key = "Epidemic:cities";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }

        $cities = $this->getResult();
        if (empty($cities)) {
            return 0;
        }
        if (Cache::has($collapse_cache_key)) {
            $city_format = Cache::get($collapse_cache_key);
        } else {
            $data = array_column($cities, 'citys');
            // 数组展开
            $city_format = collect($data)->collapse()->toArray();
            Cache::put($collapse_cache_key, $city_format, config('trip.ttl.day') * 10);
        }
        $res = collect($city_format)->firstWhere('city', $name);
        if (!isset($res['city_id'])) {
            return 0;
        }

        $city_id = $res['city_id'];
        Cache::put($cache_key, $city_id, config('trip.ttl.day') * 10);
        return $city_id;
    }


    /**
     * @throws Exception
     */
    public function getResult()
    {
        if (!file_exists($this->file)) {
            throw new Exception('Epidemic/city.json not exist');
        }
        $res = json_decode(file_get_contents($this->file), true);
        return $res ?: [];
    }
}